<template>
  <div class="addbase">
       <h4>养殖基地管理> {{info}}养殖基地</h4>
       <div class="container" style="padding:0;">
          <div class="baseInfo">
               <h4>{{info}}养殖基地信息</h4>
                <div class="info">
                     <div class="demo-input-suffix">
                                基地名称：
                                <el-input
                                    placeholder="请输入基地名称"
                                    v-model="baseName" class="filter-input">
                                </el-input>
                      </div>
                      <div class="demo-input-suffix" style="position:relative;">
                           <div class="left" style="position:absolute;left:0;
                           top:0;display:inline-block;">地区选择:</div>
                           <div class="areaBox" style="display:inline-block;padding-top:8px;height:34px;padding-left:54px;">
                               <area-select :level="2" v-model="selected" :data="$pcaa" ></area-select> 
                            </div>    
                      </div>
                      <div class="demo-input-suffix">
                                详细地址：
                                <el-input
                                    placeholder="请输入详细地址"
                                    v-model="detailAdress" class="filter-input">
                                </el-input>
                      </div>
                </div>
                 <div class="rz_btn" style="padding: 60px;" v-if="!isService">
                    <el-button type="info" @click="cancel()">取消</el-button> 
                    <el-button type="primary" style="margin-left: 20px;" @click="handleSave()">保存</el-button>
                </div>
                <h4 v-if="isService">服务区域</h4>
                <div v-if="isService">
                    <el-button type="primary" style="margin-left: 20px;" @click="add()">新增</el-button>
                    <el-tabs v-model="editableTabsValue"  closable @edit="handleTabsEdit" tab-position="left"  type="border-card"
                             @tab-click="changeBase">
                           <el-tab-pane :key="item.name" v-for="(item, index) in editableTabs"
                                    :label="item.label" :name="item.value"  @edit="handleTabsEdit">
                            <el-table :data="tableData" border  style="width: 100%">
                                <!-- <el-table-column prop="deliveryFeeDis" label="服务费折扣"></el-table-column> -->
                                <el-table-column prop="cityName"  label="地级市" width="180" :header-cell-style="rowClass"></el-table-column>
                                <el-table-column prop="districtName"  label="市辖区/县/县级市"  width="180"></el-table-column>
                                <el-table-column prop="deliveryTime" label="预计物流时间"></el-table-column>
                                <el-table-column prop="deliveryFee"  label="物流费"></el-table-column>
                                <el-table-column prop="deliveryFeeDis" label="物流费折扣"></el-table-column>
                                <el-table-column prop="deliveryFee"  label="服务费"></el-table-column>
                                <el-table-column prop="deliveryFeeDis" label="服务费折扣"></el-table-column>
                                <el-table-column label="操作"  align="center">
                                    <template slot-scope="scope">
                                        <el-button size="mini" type="warning" @click="handleEdit(scope.row)">编辑</el-button>
                                        <el-button size="mini" type="danger" @click="handleDel( scope.row.id)">删除</el-button>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="deliveryFeeDis" label="服务费折扣">
                                    <template slot-scope="scope">
                                        <el-button size="mini" type="danger" @click="handleEdit(scope.row)">新增</el-button>
                                        <el-button size="mini" type="danger" @click="handleDel( scope.row.id)">查看>></el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </el-tab-pane>
                    </el-tabs>
                </div>
          </div> 
      </div>
      <!-- 新增服务区的弹框 -->
      <el-dialog title="新增服务区" :visible.sync="dialogFormVisible" width="40%">
            <el-form  :model="formInfo" :rules="rules" ref="formInfo">
                <el-form-item prop="selected" label="服务地区选择" :label-width="formLabelWidth">
                     <area-select :level="2" v-model="formInfo.selected"  :data="$pcaa" ></area-select> 
                </el-form-item>
                <el-form-item prop="wlHour" label="预计物流时间(/h)" :label-width="formLabelWidth">
                      <el-input v-model="formInfo.wlHour"  auto-complete="off" class="input-item"> </el-input>
                </el-form-item>
                <el-form-item prop="wlMoney" label="物流费(元/斤)" :label-width="formLabelWidth">
                      <el-input v-model="formInfo.wlMoney" auto-complete="off" class="input-item"></el-input>
                </el-form-item>
                <el-form-item prop="zk" label="物流费折扣(/折)" :label-width="formLabelWidth">
                      <el-input v-model="formInfo.zk" auto-complete="off" class="input-item"></el-input>
                      (请输入0~1之间的数字)
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save('formInfo')">确 定</el-button>
            </div>
       </el-dialog>
  
  </div>
</template>

<script>
import { d,add_base,baseById,update_base,get_province,add_service,serviceList,delService,del_service,edit_service } from '@/request/api'
import abc from './area.vue'
import { AreaSelect } from "vue-area-linkage";
export default {
    data(){
         var checkBlank = (rule, value, callback) => {
            if (/(^\s+)|(\s+$)|\s+/g.test(value)) {
                callback(new Error('请不要输入空格'));
            }else {
                callback()
            } 
        };
        return {
           baseName:'',
           detailAdress:'',
           selected: [],
           info:'',
           tableData: [],
          editableTabsValue: '2',
          editableTabs: [], // tab栏数据
          tabIndex: 2,
          dialogFormVisible:false,
          formInfo:{
            isEdit:false,
            selected:[],
            wlHour:'',
            wlMoney:'',
            zk:'',
            id:''
          },
          formLabelWidth:'140px',
          rules:{
                wlHour: [
                    { required: true, message: '预计物流时间不能为空', trigger: 'blur' },
                        { validator: checkBlank, trigger: 'blur' }
                ],
                wlMoney: [
                    { required: true, message: '物流费不能为空', trigger: 'change' },
                    { validator: checkBlank, trigger: 'blur' }
                ],
                zk: [
                    {  required: true, message: '折扣不能为空', trigger: 'change' },
                    { pattern:/(^0.[0-9]{1,2}$)|(^1.[0]{1,2}$)|(^0$)|(^1$)/, message: '折扣格式不对', trigger: 'blur'}
                ],
                selected: [
                    { required: true, message: '不能为空', trigger: 'blur' }
                ],
          },
          isService:false // 是否显示服务区
        }
    },
    components:{
        AreaSelect
    },
    created(){
        d().then(res => {
             console.log(res);
        })
         var path = this.$route.fullPath;
         if(path.indexOf('/base/edit') != -1) {
            // 编辑页面 数据回显 
            this.info = '编辑'
            // 数据回显 根据id
            this.isService = false;
            this.getDetail()
         }else if(path.indexOf('/base/detail') != -1) {
            //  详情页面 需要隐藏取消 保存按钮
             this.info = '详情'
             this.isService = true;
             this.getDetail()
         }else {
            //  新增页面 
             this.info = '新增'
             this.isService = false;
         }
        //  查询服务区省
        this.get_provinceList();
         
    },
    methods:{
      getDetail(){
           let id = this.$route.params.id;
            console.log(id);
            baseById({
               id
            }).then(res =>{
                if(res.code == 1) {
                    this.baseName = res.data.baseName;
                    this.selected = ['320000', '320800', '320830']
                    this.selected = [res.data.provinceId.toString(),res.data.cityId.toString(),res.data.districtId.toString()];
                    console.log(this.selected);
                    this.detailAdress = res.data.address;
                }
            })
      },
      rowClass({ row, rowIndex}) {
            alert(1);
            console.log(rowIndex) //表头行标号为0
            return 'background:#ebeef5'
      },
      handleSave(){
        if(this.baseName == '') {
            this.$message({
                message: '请填写基地名称',
                type: 'warning'
           });
            return false;
        }
        if(!this.selected[0]) {
            this.$message({
                message: '请选择省',
                type: 'warning'
           });
            return false;
        }
        console.log(this.selected[1]);
         if(!this.selected) {
            this.$message({
                message: '请选择市',
                type: 'warning'
           });
            return false;
        }
         if(!this.selected[2]) {
              this.$message({
                message: '请选择区',
                type: 'warning'
             });
            return false;
        }
         if(this.detailAdress == '') {
              this.$message({
                message: '请填写详细地址',
                type: 'warning'
           });
            return false;
        }
         if(this.$route.fullPath.indexOf('/base/edit') != -1) {
            //  编辑 接口
           
            update_base( {
                baseName:this.baseName,
                provinceId:this.selected[0],
                cityId:this.selected[1],
                districtId:this.selected[2],
                street:this.detailAdress,
                id:this.$route.params.id
            }).then(res => {
               if(res.code ==1) {
                    this.$message({
                        message: '编辑成功',
                        type: 'success'
                    });
                    this.$router.push({
                        path:'/base'
                    })
               }
            })
         }else {
             //   新增接口
          
            add_base( {
                    baseName:this.baseName,
                    provinceId:this.selected[0],
                    cityId:this.selected[1],
                    districtId:this.selected[2],
                    street:this.detailAdress
            }).then(res => {
               if(res.code ==1) {
                    this.$message({
                        message: '新增成功',
                        type: 'success'
                    });
                    this.$router.push({
                        path:'/base'
                    })
               }
               if(res.code == 3) {
                    this.$message({
                        message: '该地区已存在',
                        type:'info'
                    }); 
                }
            })
         }
           
      },
      cancel(){
          this.$router.go(-1);
      },
      handleEdit(obj){
          this.formInfo.id = obj.id;
          this.dialogFormVisible = true;
          this.formInfo.selected = [obj.provinceId.toString(),obj.cityId.toString(),obj.districtId.toString()];
          this.formInfo.wlHour = obj.deliveryTime;
          this.formInfo.wlMoney = obj.deliveryFee;
          this.formInfo.zk = obj.deliveryFeeDis;
          this.formInfo.isEdit = true;
      },
      handleDel(id){
          this.$confirm("此操作将永久删除, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
         }).then(()=>{
                delService({
                        id:id,
                }).then(res => {
                     if(res.code == 1) {
                        this.$message({
                                type: 'success',
                                message: '删除成功!'
                        });
                        this.getTable();
                        // 表格刷新  
                        //  左边 tab 栏 刷新  
                        this.get_provinceList();
                     }
                })
         }).catch(()=>{
              this.$message({
                    type: 'info',
                    message: '已取消删除'
              });  
         }) 
     
      },
      add(){
         this.dialogFormVisible = true;     
      },
      save(formName) {
          this.$refs[formName].validate(valid => {
               if(valid) {
                   if(this.formInfo.isEdit) {
                       if(this.formInfo.selected[0] != this.editableTabsValue)  {
                           alert('选择的省市只能是当前省份')
                           return false;
                       }
                       edit_service({
                            id:this.formInfo.id,
                            belongBase: this.$route.params.id,
                            provinceId:this.formInfo.selected[0],
                            cityId:this.formInfo.selected[1],
                            districtId:this.formInfo.selected[2],
                            deliveryTime:this.formInfo.wlHour,
                            deliveryFee:this.formInfo.wlMoney, //物流费
                            deliveryFeeDis:this.formInfo.zk // 物流费折扣
                       }).then(res => {
                           if(res.code == 1) {
                                this.$message({
                                    message: '修改成功',
                                    type: 'success'
                                });
                                //   请空数据 
                                this.dialogFormVisible = false;
                                this.formInfo.selected = [];
                                this.formInfo.zk = '';
                                this.formInfo.wlHour = '';
                                this.formInfo.wlMoney = '';
                                this.formInfo.isEdit = false;
                                this.formInfo.id = '';
                                this.get_provinceList();
                          }
                         if(res.code == 2 ) {
                              this.$message({
                                    message: '该地区已被设置服务区,重新选择地区',
                                    type:'info'
                              });  
                          }
                         
                       })
                   }else {
                        add_service({
                            belongBase: this.$route.params.id,
                            provinceId:this.formInfo.selected[0],
                            cityId:this.formInfo.selected[1],
                            districtId:this.formInfo.selected[2],
                            deliveryTime:this.formInfo.wlHour,
                            deliveryFee:this.formInfo.wlMoney, //物流费
                            deliveryFeeDis:this.formInfo.zk // 物流费折扣
                        }).then(res => {
                            if(res.code == 1) {
                                this.$message({
                                    message: '新增成功',
                                    type: 'success'
                                });
                                //   请空数据 
                                this.dialogFormVisible = false;
                                this.formInfo.selected = [];
                                this.formInfo.zk = '';
                                this.formInfo.wlHour = '';
                                this.formInfo.wlMoney = '';
                                this.get_provinceList();
                            }
                            if(res.code == 2 ) {
                                this.$message({
                                        message: '该地区已被设置服务区,重新选择地区',
                                        type:'info'
                                });  
                            }
                            
                        })
                   }
               }
          })
      },
      changeBase(){
          console.log(this.editableTabsValue);
          serviceList({
              baseId:this.$route.params.id,
              id:this.editableTabsValue,
              pageSize:10,
              pageNum:1
          }).then(res => {
               console.log(res);
               this.tableData = res.rows;
          })

      },
      handleTabsEdit(){
    //   删除所有省 下面的列表
                del_service({
                        provinceId:this.editableTabsValue,
                        baseId:this.$route.params.id
                }).then(res => {
                     if(res.code == 1) {
                        this.$message({
                                type: 'success',
                                message: '删除成功!'
                        });
                       this.get_provinceList();
                     }
                })
      
      },
      getTable(){
          serviceList({
              baseId:this.$route.params.id,
              id:this.editableTabsValue,
              pageSize:10,
              pageNum:1
          }).then(res => {
               console.log(res);
               this.tableData = res.rows;
          })
      },
      get_provinceList(){
          get_province({
              baseId:this.$route.params.id
          }).then(res => {
              console.log(res);
              this.editableTabs = res.data.map(v=> {
                   v.value = v.value.toString();
                   return v;
              });
              this.editableTabsValue = this.editableTabs[0].value;
               this.getTable();
         })
      }
    }
 }
</script>
<style  scoped>
.input-item {
    width: 200px;
}
.addbase > h4 {
    line-height: 22px;
    border-left: 5px solid rgb(32, 160, 255);
    font-size:16px;
    color: #666;
    padding-left:  10px;
    font-size:18px;
    margin-bottom:20px;
}
.container {
    line-height:50px;
    border-radius: 0;
}
.container h4 {
    background-color: #eee;
    line-height: 50px;
    font-weight: 400;
    font-size:16px;
    padding-left:30px;
    color: #999;

}
.container .info {
    padding: 0  60px;
}
.filter-input {
    width:360px;
    display: inline-block;
}
</style>